﻿using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

namespace Framework
{
    public class ImageExtension
    {

        /// <summary>
        /// 图片参数预定义
        /// </summary>
        private static readonly Hashtable Htmimes = new Hashtable();
        /// <summary>
        /// 会产生graphics异常的PixelFormat
        /// </summary>
        private static readonly PixelFormat[] IndexedPixelFormats =
            {
                PixelFormat.Undefined, PixelFormat.DontCare,
                PixelFormat.Format16bppArgb1555, PixelFormat.Format1bppIndexed, PixelFormat.Format4bppIndexed,
                PixelFormat.Format8bppIndexed
            };
        internal static readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp|.gif";
        public static Color Background;
        public static Color Border;
        public static string MarkPosition;
        public static int Quality;
        public static Color Shadow;

        static ImageExtension()
        {
            Background = Color.Transparent;
            Border = Color.Transparent;
            Shadow = Color.Transparent;
            Quality = 100;
            MarkPosition = "左下角";
            #region 图片类型预定义
            Htmimes[".jpe"] = "image/jpeg";
            Htmimes[".jpeg"] = "image/jpeg";
            Htmimes[".jpg"] = "image/jpeg";
            Htmimes[".png"] = "image/png";
            Htmimes[".tif"] = "image/tiff";
            Htmimes[".tiff"] = "image/tiff";
            Htmimes[".bmp"] = "image/bmp";
            Htmimes[".gif"] = "image/gif";
            #endregion
        }

        #region 下载指定URL图片并保存
        /// <summary>
        /// 判断图片的PixelFormat 是否在 引发异常的 PixelFormat 之中
        /// </summary>
        /// <param name="imgPixelFormat">原图片的PixelFormat</param>
        /// <returns></returns>
        public static bool IsPixelFormatIndexed(PixelFormat imgPixelFormat)
        {
            return IndexedPixelFormats.Contains(imgPixelFormat);
        }
        /// <summary>
        ///  下载指定URL的文件并保存到指定目录
        /// </summary>
        /// <param name="strUrl"></param>
        /// <param name="file"></param>
        public static void DownloadImage(string strUrl, string file)
        {
            var wc = new WebClient();
            wc.DownloadFile(strUrl, file);
        }

        #endregion

        #region C#自动生成缩略图
        /// <summary>
        /// 按给定名字确定颜色
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Color ToColor(string name)
        {
            if (name == "白色") return Color.White;
            if (name == "红色") return Color.Red;
            if (name == "蓝色") return Color.Blue;
            if (name == "绿色") return Color.Green;
            if (name == "黑色") return Color.Black;
            if (name == "灰色") return Color.DarkGray;
            if (name == "黄色") return Color.Yellow;
            if (name == "紫色") return Color.Cyan;
            if (name == "无色") return Color.Transparent;
            return Color.Transparent;
        }
        /// <summary>
        /// 按名字设置各种颜色，可以自行扩充:)
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static int ToQuality(string name)
        {
            return Int32.Parse(name.Replace("%", ""));
        }

        /// <summary> 
        /// 获取图像编码解码器的所有相关信息 
        /// </summary> 
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param> 
        /// <returns>返回图像编码解码器的所有相关信息</returns> 
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] codecInfo = ImageCodecInfo.GetImageEncoders();
            return codecInfo.FirstOrDefault(ici => ici.MimeType == mimeType);
        }

        /// <summary> 
        /// 检测扩展名的有效性 
        /// </summary> 
        /// <param name="sExt">文件名扩展名</param> 
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns> 
        private static bool CheckValidExt(string sExt)
        {
            string[] aExt = AllowExt.Split(Convert.ToChar("|"));
            return aExt.Any(filetype => filetype.ToLower() == sExt);
        }

        /// <summary> 
        /// 保存图片 
        /// </summary> 
        /// <param name="image">Image 对象</param> 
        /// <param name="savePath">保存路径</param> 
        /// <param name="ici">指定格式的编解码参数</param> 
        private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
        {
            //设置 原图片 对象的 EncoderParameters 对象 
            var parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(Encoder.Quality, (Quality));
            image.Save(savePath, ici, parameters);
            parameters.Dispose();
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourceImagePath">原图片路径(相对路径)</param> 
        /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
        /// <param name="maxThumbnailImageHeight"> </param>
        /// <param name="maxThumbnailImageWidth"> </param>
        public static void ToThumbnail(string sourceImagePath, string thumbnailImagePath, int maxThumbnailImageHeight,
        int maxThumbnailImageWidth)
        {
            string sExt = sourceImagePath.Substring(sourceImagePath.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
            if (sourceImagePath == String.Empty)
            {
                throw new NullReferenceException("原图片路径不能为空!");
            }
            if (!CheckValidExt(sExt))
            {
                throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]");
            }
            // 从原图片创建 Image 对象 
            string fiepath = Path.IsPathRooted(sourceImagePath) ? sourceImagePath : HttpContext.Current.Server.MapPath(sourceImagePath);
            if (!File.Exists(fiepath))
                return;
            Image image = Image.FromFile(fiepath);
            if (image.Height <= maxThumbnailImageHeight && image.Width <= maxThumbnailImageWidth)
            {
                image.Save(thumbnailImagePath);
                image.Dispose();
            }
            else
            {
                double fs = (image.Height * 1.0 / maxThumbnailImageHeight) > (image.Width * 1.0 / maxThumbnailImageWidth)
                ? (image.Height * 1.0 / maxThumbnailImageHeight)
                : (image.Width * 1.0 / maxThumbnailImageWidth);
                var thumbnailImageHeight = (int)(image.Height / fs);
                var thumbnailImageWidth = (int)(image.Width / fs);
                // .计算图片的位置、尺寸等信息

                int tWidth = thumbnailImageWidth;
                int tHeight = thumbnailImageHeight;
                const int tLeft = 0;
                const int tTop = 0;
                //用指定的大小和格式初始化 Bitmap 类的新实例 
                //Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.FormatbppArgb);
                var bitmap = new Bitmap(thumbnailImageWidth, thumbnailImageHeight, PixelFormat.Format32bppArgb);
                //从指定的 Image 对象创建新 Graphics 对象 
                Graphics graphics = Graphics.FromImage(bitmap);
                //清除整个绘图面并以透明背景色填充
                graphics.Clear(Background != Color.Transparent ? Background : Color.Transparent);

                graphics.InterpolationMode = InterpolationMode.High;
                //在指定位置并且按指定大小绘制 原图片 对象 
                graphics.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
                graphics.DrawImage(image, new Rectangle(tLeft, tTop, tWidth, tHeight));
                image.Dispose();
                try
                {
                    //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件 
                    if (String.IsNullOrEmpty(thumbnailImagePath)) return;
                    // 从原图片创建 Image 对象 
                    string savepath = Path.IsPathRooted(thumbnailImagePath) ? thumbnailImagePath : HttpContext.Current.Server.MapPath(thumbnailImagePath);
                    SaveImage(bitmap, savepath, GetCodecInfo((string)Htmimes[sExt]));
                }
                finally
                {
                    bitmap.Dispose();
                    graphics.Dispose();
                }
            }
        }

        /// <summary> 
        /// 生成缩略图 
        /// </summary> 
        /// <param name="sourceImagePath">原图片路径(相对路径)</param> 
        /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param> 
        /// <param name="thumbnailImageWidth">缩略图的宽度（高度与按源图片比例自动生成）</param>
        /// <param name="thumbnailImageHeight"></param>
        /// <param name="model">图片缩放模式(model=1 自适应 model=2 拉伸 model=3 裁剪)</param> 
        public static void ToThumbnail(string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth,
        int thumbnailImageHeight, int model)
        {
            // .先检查图片格式等信息
            string thumbnailImagePathNew = thumbnailImagePath;
            string sourceImagePathNew = sourceImagePath;
            string sExt = sourceImagePathNew.Substring(sourceImagePathNew.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
            if (sourceImagePathNew == String.Empty)
            {
                throw new NullReferenceException("SourceImagePath is null!");
            }
            if (!CheckValidExt(sExt))
            {
                throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]");
            }
            // 从原图片创建 Image 对象 
            Image image = Image.FromFile(HttpContext.Current.Server.MapPath(sourceImagePathNew));
            // .计算图片的位置、尺寸等信息
            int tWidth, tHeight, tLeft, tTop;
            if (model == 1)
            {
                double fScale = thumbnailImageHeight / (double)thumbnailImageWidth; // 高度宽度比
                if ((image.Width * fScale) > image.Height) // 如果原图比较宽
                {
                    tWidth = thumbnailImageWidth;
                    tHeight = (int)(image.Height * (double)tWidth / image.Width);
                    tLeft = 0;
                    tTop = (thumbnailImageHeight - tHeight) / 2;
                }

                else
                {
                    tHeight = thumbnailImageHeight;
                    tWidth = (int)(image.Width * (double)tHeight / image.Height);
                    tLeft = (thumbnailImageWidth - tWidth) / 2;
                    tTop = 0;
                }

                if (tLeft < 0) tLeft = 0;

                if (tTop < 0) tTop = 0;

                if (Border != Color.Transparent)
                {
                    tWidth -= 2;
                    tHeight -= 2;
                    tLeft++;
                    tTop++;
                }

                if (Shadow != Color.Transparent)
                {
                    tWidth -= 1;
                    tHeight -= 1;
                }
            }
            else if (model == 2)
            {
                tWidth = thumbnailImageWidth;
                tHeight = thumbnailImageHeight;
                tLeft = 0;
                tTop = 0;
            }
            else
            {
                tWidth = thumbnailImageWidth;
                tHeight = thumbnailImageHeight;
                tLeft = 0;
                tTop = 0;
            }

            //用指定的大小和格式初始化 Bitmap 类的新实例 
            //Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.FormatbppArgb);
            var bitmap = new Bitmap(thumbnailImageWidth, thumbnailImageHeight, PixelFormat.Format32bppArgb);
            //从指定的 Image 对象创建新 Graphics 对象 
            Graphics graphics = Graphics.FromImage(bitmap);
            //清除整个绘图面并以透明背景色填充
            graphics.Clear(Background != Color.Transparent ? Background : Color.Transparent);
            // 添加阴影
            if (Shadow != Color.Transparent)
            {
                var shPen = new Pen(Shadow);
                graphics.DrawLine(shPen, new Point(1, thumbnailImageHeight - 1),
                new Point(thumbnailImageWidth - 1, thumbnailImageHeight - 1));
                graphics.DrawLine(shPen, new Point(thumbnailImageWidth - 1, 1),
                new Point(thumbnailImageWidth - 1, thumbnailImageHeight - 1));
            }

            // 添加边框

            if (Border != Color.Transparent)
            {
                var bdPen = new Pen(Border);
                graphics.DrawRectangle(bdPen,
                 Shadow != Color.Transparent
                 ? new Rectangle(0, 0, thumbnailImageWidth - 2, thumbnailImageHeight - 2)
                 : new Rectangle(0, 0, thumbnailImageWidth - 1, thumbnailImageHeight - 1));
            }

            graphics.InterpolationMode = InterpolationMode.High;
            //在指定位置并且按指定大小绘制 原图片 对象 
            graphics.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
            graphics.DrawImage(image, new Rectangle(tLeft, tTop, tWidth, tHeight));
            image.Dispose();
            try
            {
                //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件 
                string savepath = (String.IsNullOrEmpty(thumbnailImagePathNew) ? sourceImagePathNew : thumbnailImagePathNew);
                SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo((string)Htmimes[sExt]));
            }
            finally
            {
                bitmap.Dispose();
                graphics.Dispose();
            }
        }

        #endregion

        #region C#给图片添加水印

        public static void Mark(string sourceImagePath, string markString)
        {
            // .先检查图片格式等信息

            string sourceImagePathNew = sourceImagePath;
            if (sourceImagePathNew == null) throw new ArgumentException("原图片路劲不能为空");
            string sExt = sourceImagePathNew.Substring(sourceImagePathNew.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
            if (sourceImagePathNew == String.Empty)
            {
                throw new NullReferenceException("SourceImagePath is null!");
            }
            if (!CheckValidExt(sExt))
            {
                throw new ArgumentException("原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]");
            }
            // 从原图片创建 Image 对象 
            Image image = Image.FromFile(HttpContext.Current.Server.MapPath(sourceImagePathNew));
            //用指定的大小和格式初始化 Bitmap 类的新实例 
            var bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
            //从指定的 Image 对象创建新 Graphics 对象 
            Graphics graphics = Graphics.FromImage(bitmap);
            //在指定位置并且按指定大小绘制 原图片 对象 
            graphics.InterpolationMode = InterpolationMode.High;
            //在指定位置并且按指定大小绘制 原图片 对象 
            graphics.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
            graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
            #region 绘制水印
            // 设置水印字体
            int fHeight = image.Height / 5;
            if (fHeight > 16) fHeight = 16;
            var drawFont = new Font("Arial", fHeight);
            // 设置水印文字位置，默认为左下角
            float x = 4;
            float y = image.Height - drawFont.Height - 4;
            if (MarkPosition == "左上角")
            {
                y = 4;
            }
            if (MarkPosition == "右上角")
            {
                x = image.Width - markString.Length * fHeight / 2 - fHeight;
                y = 4;
            }
            if (MarkPosition == "右下角")
            {
                x = image.Width - markString.Length * fHeight / 2 - fHeight;
            }
            if (MarkPosition == "图片中间")
            {
                x = image.Width / 2 - markString.Length * fHeight / 2;
                y = image.Height / 2 - fHeight / 2;
            }
            var drawFormat = new StringFormat { FormatFlags = StringFormatFlags.NoWrap };
            // 设置水印文字颜色，先绘制一个黑色字作为阴影，再绘制白色字，这样比较显眼；
            var drawBrush = new SolidBrush(Color.Black);
            graphics.DrawString(markString, drawFont, drawBrush, x, y, drawFormat);
            drawBrush.Color = Color.White;
            graphics.DrawString(markString, drawFont, drawBrush, x - 1, y - 1, drawFormat);
            #endregion
            image.Dispose();
            try
            {
                //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件 
                string savepath = sourceImagePathNew;
                SaveImage(bitmap, HttpContext.Current.Server.MapPath(savepath), GetCodecInfo((string)Htmimes[sExt]));
            }
            finally
            {
                bitmap.Dispose();
                graphics.Dispose();
            }
        }

        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="path">原服务器图片路径</param>
        /// <param name="pathSyp">生成的带图片水印的图片路径</param>
        /// <param name="pathSypf">水印图片路径</param>
        public static void Mark(string path, string pathSyp, string pathSypf)
        {
            Image image = Image.FromFile(path);
            Image copyImage = Image.FromFile(pathSypf);
            Graphics g = Graphics.FromImage(image);
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
            g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            g.Dispose();
            image.Save(pathSyp);
            image.Dispose();
        }
        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="stream">原服务器图片</param>
        /// <param name="pathSyp">生成的带图片水印的图片路径</param>
        /// <param name="pathSypf">水印图片路径</param>
        public static void Mark(Stream stream, string pathSyp, string pathSypf)
        {
            Mark(stream, pathSyp, pathSypf, FillMode.Title);
        }

        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="stream">原服务器图片</param>
        /// <param name="pathSyp">生成的带图片水印的图片路径</param>
        /// <param name="pathSypf">水印图片路径</param>
        /// <param name="fillMode"> </param>
        public static void Mark(Stream stream, string pathSyp, string pathSypf, FillMode fillMode)
        {
            Image image = Image.FromStream(stream);
            Image copyImage = Image.FromFile(pathSypf);
            ImageFillRect(copyImage, image, FillMode.Title);
            image.Save(pathSyp);
            copyImage.Dispose();
            image.Dispose();
        }
        #endregion

        /// <summary>
        /// 二进制数据流转为图片
        /// </summary>
        /// <param name="bt">图片数据流</param>
        /// <returns>图片</returns>
        public static Bitmap ImageFromByte(byte[] bt)
        {
            if (bt != null && bt.Length > 0)
            {
                using (var stream = new MemoryStream(bt, true))
                {
                    stream.Write(bt, 0, bt.Length);
                    return new Bitmap(stream);
                }
            }
            return PrepareDefaultImage();
        }

        /// <summary>
        /// 图片转为二进制数据流    
        /// </summary>
        /// <param name="bm">图片</param>
        /// <returns></returns>
        public static byte[] ByteFromImage(Bitmap bm)
        {
            using (var stream = new MemoryStream())
            {
                bm.Save(stream, bm.RawFormat);
                return stream.GetBuffer();
            }
        }

        /// <summary>
        /// 生成默认图片
        /// </summary>
        /// <returns></returns>
        public static Bitmap PrepareDefaultImage()
        {
            var image = new Bitmap(90, 120);
            Graphics g = Graphics.FromImage(image);
            try
            {
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
                g.Clear(Color.White);
                var font = new Font("黑体", 10, (FontStyle.Bold));
                var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.OrangeRed, Color.OrangeRed, 1.2f, true);
                g.DrawString("暂无图片", font, brush, 15, 50);
                var ms = new MemoryStream();
                image.Save(ms, ImageFormat.Gif);
                g.Dispose();
                image.Dispose();
                return new Bitmap(ms);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 从文字生成图片
        /// </summary>
        /// <param name="filename">图片保存文件名</param>
        /// <param name="myText">文字</param>
        /// <param name="with">宽</param>
        /// <param name="height">高</param>
        /// <param name="fontname">字体</param>
        /// <param name="fontsize">字体大小</param>
        /// <param name="color">字体颜色</param>
        /// <param name="imgType"> </param>
        public static void GenerateImgFromText(string filename, string myText, int with, int height, string fontname, int fontsize, Color color, string imgType)
        {
            Image img = new Bitmap(with, height);
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(imgType == ".png" ? Color.Transparent : Color.LightGray);
            var f = new Font(fontname, fontsize);
            SizeF crSize = g.MeasureString(myText, f);
            float xpos = (img.Width * (float).50) - (crSize.Width / 2);
            float ypos = (img.Height * (float).50) - (crSize.Height / 2);
            g.DrawString(myText, f, new SolidBrush(color), xpos, ypos);
            img.Save(filename);
            //回收资源  
            g.Dispose();
            img.Dispose();
        }
        public enum FillMode
        {
            /// <summary>
            /// 平铺
            /// </summary>
            /// <remarks></remarks>
            Title = 0,
            /// <summary>
            /// 居中
            /// </summary>
            /// <remarks></remarks>
            Center = 1,
            /// <summary>
            /// 拉伸
            /// </summary>
            /// <remarks></remarks>
            Struk = 2,
            /// <summary>
            /// 缩放
            /// </summary>
            /// <remarks></remarks>
            Zoom = 3
        }
        /// <summary>
        /// 将指向图像按指定的填充模式绘制到目标图像上
        /// </summary>
        /// <param name="sourceBmp">要控制填充模式的源图</param>
        /// <param name="targetBmp">要绘制到的目标图</param>
        /// <param name="fillMode">填充模式</param>
        /// <remarks></remarks>
        public static void ImageFillRect(Image sourceBmp, Image targetBmp, FillMode fillMode)
        {
            try
            {
                switch (fillMode)
                {
                    case FillMode.Title:
                        using (var txbrus = new TextureBrush(sourceBmp))
                        {
                            txbrus.WrapMode = WrapMode.Tile;
                            using (Graphics g = Graphics.FromImage(targetBmp))
                            {
                                g.FillRectangle(txbrus, new Rectangle(0, 0, targetBmp.Width - 1, targetBmp.Height - 1));
                            }
                        }

                        break;
                    case FillMode.Center:
                        using (Graphics g = Graphics.FromImage(targetBmp))
                        {
                            g.InterpolationMode = InterpolationMode.High;
                            g.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
                            int xx = (targetBmp.Width - sourceBmp.Width) / 2;
                            int yy = (targetBmp.Height - sourceBmp.Height) / 2;
                            g.DrawImage(sourceBmp, new Rectangle(xx, yy, sourceBmp.Width, sourceBmp.Height), new Rectangle(0, 0, sourceBmp.Width, sourceBmp.Height), GraphicsUnit.Pixel);
                        }

                        break;
                    case FillMode.Struk:
                        using (Graphics g = Graphics.FromImage(targetBmp))
                        {
                            g.InterpolationMode = InterpolationMode.High;
                            g.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
                            g.DrawImage(sourceBmp, new Rectangle(0, 0, targetBmp.Width, targetBmp.Height), new Rectangle(0, 0, sourceBmp.Width, sourceBmp.Height), GraphicsUnit.Pixel);
                        }

                        break;
                    case FillMode.Zoom:
                        double tm;
                        int w = sourceBmp.Width;
                        int h = sourceBmp.Height;
                        if (w > targetBmp.Width)
                        {
                            tm = (double)targetBmp.Width / sourceBmp.Width;
                            w = (int)(w * tm);
                            h = (int)(h * tm);
                        }
                        if (h > targetBmp.Height)
                        {
                            tm = (double)targetBmp.Height / h;
                            w = (int)(w * tm);
                            h = (int)(h * tm);
                        }
                        using (var tmpBp = new Bitmap(w, h))
                        {
                            using (Graphics g2 = Graphics.FromImage(tmpBp))
                            {
                                g2.InterpolationMode = InterpolationMode.High;
                                g2.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
                                g2.DrawImage(sourceBmp, new Rectangle(0, 0, w, h), new Rectangle(0, 0, sourceBmp.Width, sourceBmp.Height), GraphicsUnit.Pixel);
                                using (Graphics g = Graphics.FromImage(targetBmp))
                                {
                                    g.InterpolationMode = InterpolationMode.High;
                                    g.SmoothingMode = SmoothingMode.HighQuality;//消除锯齿
                                    int xx = (targetBmp.Width - w) / 2;
                                    int yy = (targetBmp.Height - h) / 2;
                                    g.DrawImage(tmpBp, new Rectangle(xx, yy, w, h), new Rectangle(0, 0, w, h), GraphicsUnit.Pixel);
                                }
                            }
                        }

                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}